package com.benzhuo.widget.research.recycler;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.AttributeSet;
import android.view.ViewParent;

import com.benzhuo.widget.research.refresh.PullRefreshView;

/**
 * Created by WuWangchun on 2016/7/28.
 */
public class ZPullRefreshView extends ZLoadRecyclerView implements PullRefreshView.OnRefreshListener {

    private boolean hasSetRefreshLayout;
    private IRefreshListener refreshListener;
    private PullRefreshView refreshLayout;

    public ZPullRefreshView(Context context) {
        super(context);
    }

    public ZPullRefreshView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ZPullRefreshView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if (!hasSetRefreshLayout){
            hasSetRefreshLayout=true;
            ViewParent vp = getParent();
            if (vp!=null && vp instanceof PullRefreshView){
                refreshLayout=(PullRefreshView) vp;
                refreshLayout.removeView(this);
                refreshLayout.setTagetView(this);
                refreshLayout.setOnRefreshListener(this);
            }else {
//                throw new IllegalArgumentException("ViewParent is not SwipeRefreshLayout");
            }
        }

    }

    @Override
    public void onRefresh(PullRefreshView refreshView) {
        if (refreshListener!=null){
            if (!isLoading()){
                setLoading(true);
                setNoMore(false);
                refreshListener.refreshData(this);
            }
        }
    }

    public void refreshFinish(){
        setLoading(false);
        if (refreshLayout!=null){
            refreshLayout.refreshFinish();
        }
    }


    public IRefreshListener getRefreshListener() {
        return refreshListener;
    }

    public void setRefreshListener(IRefreshListener refreshListener) {
        this.refreshListener = refreshListener;
    }

    public interface IRefreshListener{
        void refreshData(final ZPullRefreshView recyclerView);
    }


}
